<?php

namespace app\services;

use app\payment\PayFactory;
use app\traits\Page;
use BaconQrCode\Encoder\QrCode;
use plugin\admin\app\model\Activity;
use plugin\admin\app\model\ActivityCategory;
use plugin\admin\app\model\ActivityImage;
use plugin\admin\app\model\Order;
use plugin\admin\app\model\User;
use plugin\admin\app\model\UserActivity;
use plugin\admin\app\model\UserCollect;
use plugin\admin\app\model\UserProfile;
use plugin\admin\app\model\UserPropertyLog;
use plugin\admin\app\model\UserSurname;
use SimpleSoftwareIO\QrCode\Generator;
use support\Redis;

class ActivityService
{
    public static function list($page, $length, $id = 0, $name = '')
    {
        $offset = ($page - 1) * $length;
        $query = Activity::select([
            'id',
            'thumbs',
            'price',
            'min_count',
            'max_count',
            'freeze_count',
            'join_count',
            'title',
            'desc',
            'status',
            'created_time'
        ]);

        if ($id) {
            $query = $query->where('category_id', $id);
        }

        if ($name) {
            $query = $query->where('title', 'like', "%{$name}%");
        }

        $count = (clone $query)->count();
        $list = $query->offset($offset)->limit($length)->orderByDesc('created_time')->get()->toArray();

        foreach ($list as $key=>$item) {

            $thumbs = explode(',', $item['thumbs']);

            foreach ($thumbs as $key2=>$thumb) {
                $thumbs[$key2] = full_url($thumb);
            }
            $list[$key]['thumbs'] = $thumbs;

            if (get_user_id()) {
                $list[$key]['is_collect'] = UserCollectService::isCollect(UserCollect::ACTIVITY, $item['id']);
            }

            $list[$key]['status_text'] = Activity::getStatusText($item['status']);
            $list[$key]['rest_count'] = $item['max_count'] - $item['join_count'] - $item['freeze_count'];

            $list[$key]['join_members'] = self::getJoinAvatar($item['id']);
        }

        return Page::wrap($count, $page, $length, $list);
    }

    public static function getJoinAvatar($id)
    {
        $orders = Order::select(['user_id'])->where('activity_id', $id)->whereNotNull('pay_time')->whereNull('cancel_time')->where('refund_status', 0)->orderByDesc('created_time')->get()->toArray();

        $userIds = array_column($orders, 'user_id');

        $profiles = UserProfile::select(['user_id', 'nickname', 'avatar'])->whereIn('user_id', $userIds)->get()->toArray();

        return $profiles;
    }

    public static function categories()
    {
        return ActivityCategory::select(['id', 'name'])->get()->toArray();
    }

    public static function detail($id)
    {
        $res = Activity::select([
            'id',
            'thumbs',
            'price',
            'min_count',
            'max_count',
            'join_count',
            'freeze_count',
            'start_time',
            'end_time',
            'title',
            'desc',
            'content',
            'schedule',
            'created_time',
            'shares',
            'collects',
            'status'
        ])->where('id', $id)->first();

        if (!$res) {
            throw new \Exception('不存在的活动');
        }

        $res = $res->toArray();

        $thumbs = explode(',', $res['thumbs']);

        foreach ($thumbs as $key=>$thumb) {
            $thumbs[$key] = full_url($thumb);
        }

        $res['thumbs'] = $thumbs;
        $res['content'] = str_replace('src="', 'src="' . getenv('APP_URL'), $res['content']);
        $res['schedule'] = str_replace('src="', 'src="' . getenv('APP_URL'), $res['schedule']);

        if (get_user_id()) {
            $res['is_collect'] = UserCollectService::isCollect(UserCollect::ACTIVITY, $res['id']);
        }

        $res['status_text'] = Activity::getStatusText($res['status']);
        $res['rest_count'] = $res['max_count'] - $res['join_count'] - $res['freeze_count'];
        $res['join_members'] = self::getJoinAvatar($res['id']);

        return $res;
    }

    public static function incrementCount($id, $count = 1)
    {
        Activity::where('id', $id)->increment('join_count', $count);
    }

    public static function decrementCount($id, $count = 1)
    {
        Activity::where('id', $id)->decrement('join_count', $count);
    }

    public static function collect($id)
    {
        UserCollectService::collect(UserCollect::ACTIVITY, $id, function() use ($id) {
            Activity::where('id', $id)->increment('collects');
        });
    }

    public static function uncollect($id)
    {
        UserCollectService::uncollect(UserCollect::ACTIVITY, $id, function() use ($id) {
            Activity::where('id', $id)->decrement('collects');
        });
    }

    public static function freeze($id, $count)
    {
        Activity::where('id', $id)->increment('freeze_count', $count);
    }

    public static function unfreeze($id, $count)
    {
        Activity::where('id', $id)->decrement('freeze_count', $count);
    }

    public static function share($id)
    {
        Activity::where('id', $id)->increment('shares');
    }
}